import UIKit

class UserAccount: NSObject,NSCoding {
    //用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    
    //access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //token过期的日期 
    var expires_date: NSDate?
    //当前授权用户的UID。  标识一个唯一的用户
    var uid: String?
    
    //友好显示名称
    var name: String?
    
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let Key = ["access_token","expires_in","uid","name","avatar_large"]
        let dict = self.dictionaryWithValuesForKeys(Key)
        return dict.description
    }
    //MARK: 存储模型数据
    func saveAccount() {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingString("UserAccount.plist")
        //调用归档的方法
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        print(path)
    }
    //MARK:读取模型数据
    class func loadUserAccount() -> UserAccount?{
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingString("UserAccount.plist")
        if let useraccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            //需要判断用户的token是否过期
            //只有过期日期大于当前日期 才没有过期
            if useraccount.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
                return useraccount
                
            }
        
        }
        return nil
    }
    //MARK:解归档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        //基本数据类型在解归档的时候可以得到明确类型 不需要做类型转换
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    //归档   将自定义对象 转换为二进制数据存储在沙盒中(磁盘)  -> 和序列化比较像
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
}
